package com.maybach.web.controller.product;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.audi.dubbo.api.common.enums.CarFuelEnum;
import com.audi.dubbo.api.common.enums.CarStandardEnum;
import com.audi.dubbo.api.common.enums.CarTypeEnum;
import com.audi.dubbo.api.item.request.B2BCarRequest;
import com.maybach.common.model.ImportModuleDO;
import com.maybach.common.query.ImportModuleQuery;
import com.maybach.core.ao.ImportCarAO;
import com.maybach.core.dubbo.consumer.adapter.B2BCarServiceDubboAdapter;
import com.maybach.core.manager.ImportModuleManager;

/**
 * Created by wenhua on 16/1/28.
 */
@Controller
@RequestMapping("/product")
public class ProductController {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private B2BCarServiceDubboAdapter b2BCarServiceDubboAdapter;
	@Autowired
	private ImportCarAO importCarAO;
	@Autowired
	private ImportModuleManager importModuleManager;

	@RequestMapping(value = "/import.htm")
	public String importFromExcel(ModelMap model) {
		model.addAttribute("CarTypeEnum", CarTypeEnum.class);
		model.addAttribute("CarStandardEnum", CarStandardEnum.class);
		model.addAttribute("CarFuelEnum", CarFuelEnum.class);
		return "/product/importCarsFromExcel";
	}

	@RequestMapping(value = "/importCar.htm")
	public String importCar(ModelMap model) {
		model.addAttribute("CarTypeEnum", CarTypeEnum.class);
		model.addAttribute("CarStandardEnum", CarStandardEnum.class);
		model.addAttribute("CarFuelEnum", CarFuelEnum.class);
		return "/product/importCar";
	}

	@RequestMapping(value = "/doImportModule", method = RequestMethod.POST)
	public String doImportModule(@RequestParam("default_type") int defaultType,
			@RequestParam("default_fuel") int defaultFuel, @RequestParam("default_spec") int defaultSpec,
			ModelMap model, HttpServletRequest request) {
		List<B2BCarRequest> dataList = new ArrayList<B2BCarRequest>();
		MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
		MultipartFile excelFile = mulRequest.getFile("excel");

		InputStream is = null;
		Workbook wb = null;
		try {
			is = excelFile.getInputStream();
			wb = WorkbookFactory.create(is);
			ImportModuleDO importModuleDO = null;
			ImportModuleQuery importModuleQuery = new ImportModuleQuery();
			importModuleQuery.createCriteria().andStatusEqualTo(1);
			List<ImportModuleDO> importModuleDOs = importModuleManager.selectByQuery(importModuleQuery);
			for (ImportModuleDO i : importModuleDOs) {
				if (excelFile.getOriginalFilename().contains(i.getFeature())) {
					importModuleDO = i;
					break;
				}
			}
			if (importModuleDO == null) {
				model.addAttribute("msg", "未找到符合特征值的经销商");
				return "/product/importCar";
			}
			for (int i = 0; i < wb.getNumberOfSheets(); i++) {
				Sheet sheet = wb.getSheetAt(i);
				if (sheet == null) {
					continue;
				}
				for (int j = 1; j <= sheet.getLastRowNum(); j++) {// 第四列开始导入
					Row row = sheet.getRow(j);
					if (row == null) {
						continue;
					}
					List<B2BCarRequest> b2BCarRequests = importCarAO.excelExcelCheckByModule(importModuleDO, row, j,
							defaultType, defaultFuel, defaultSpec);
					if (CollectionUtils.isNotEmpty(b2BCarRequests)) {
						dataList.addAll(b2BCarRequests);
					}
				}
			}
			Long opLogId = b2BCarServiceDubboAdapter.induceAsy(dataList);
			model.addAttribute("opLogId", opLogId);
		} catch (Exception e) {
			logger.error("", e);
		} finally {
			IOUtils.closeQuietly(is);
		}
		return "/product/importCar";
	}

	@RequestMapping(value = "/doImport", method = RequestMethod.POST)
	public String doImport(@RequestParam("default_type") int defaultType, @RequestParam("default_fuel") int defaultFuel,
			@RequestParam("default_spec") int defaultSpec, @RequestParam("type") int type, ModelMap model,
			HttpServletRequest request) {

		model.addAttribute("CarTypeEnum", CarTypeEnum.class);
		model.addAttribute("CarStandardEnum", CarStandardEnum.class);
		model.addAttribute("CarFuelEnum", CarFuelEnum.class);

		List<B2BCarRequest> dataList = new ArrayList<B2BCarRequest>();
		MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
		MultipartFile excelFile = mulRequest.getFile("excel");

		InputStream is = null;
		Workbook wb = null;
		Set<String> errList = new LinkedHashSet<String>();
		try {

			is = excelFile.getInputStream();
			wb = WorkbookFactory.create(is);

			for (int i = 0; i < wb.getNumberOfSheets(); i++) {
				Sheet sheet = wb.getSheetAt(i);
				if (sheet == null) {
					continue;
				}
				for (int j = 4; j <= sheet.getLastRowNum(); j++) {// 第四列开始导入
					Row row = sheet.getRow(j);
					if (row == null) {
						continue;
					}
					List<B2BCarRequest> b2BCarRequests = new ArrayList<B2BCarRequest>();
					if (type == 1) {
						b2BCarRequests = importCarAO.excelDataCheckByParallel(row, sheet.getSheetName(), j, errList,
								defaultType, defaultFuel, defaultSpec);
					} else {// 中规
						b2BCarRequests = importCarAO.excelDataCheckByChina(row, sheet.getSheetName(), j, errList,
								defaultType, defaultFuel);
					}
					if (CollectionUtils.isNotEmpty(b2BCarRequests)) {
						dataList.addAll(b2BCarRequests);
					}
				}
			}

			if (CollectionUtils.isNotEmpty(errList)) {
				model.addAttribute("errList", errList);
				return "/product/importCarsFromExcel";
			}
			Long opLogId = b2BCarServiceDubboAdapter.induceAsy(dataList);
			model.addAttribute("opLogId", opLogId);
		} catch (Exception e) {
			logger.error("", e);
		} finally {
			IOUtils.closeQuietly(is);
		}
		return "/product/importCarsFromExcel";
	}

}
